﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Vit.Common;
using Vit.Web.Models;
using Vit.Web.Helpers;
using Vit.Web.Extensions;
using Vit.Web.Providers;

namespace Vit.Web.SqlProviders
{
    public class SqlPortalProvider : IPortalProvider
    {
        WebProvidersDb db;

        public SqlPortalProvider(WebProvidersDb db)
        {
            this.db = db;
        }

        #region IPortalProvider Members

        public bool AddPortal(Portal portal)
        {
            db.Portals.Add(portal);
            db.SaveChanges();
            return true;
        }

        public Portal GetPortal(string portalId)
        {
            var portal = db.Portals.Where(o => o.ID == portalId)
                .Include(o => o.Sites)
                .FirstOrDefault();
            return portal;
        }

        public Portal GetCurrentPortal()
        {
            Portal portal = GetPortal("DefaultPortal");
            if (portal == null)
            {
                portal = db.Portals.FirstOrDefault();
            }
            return portal;
        }

        public bool AddSite(Portal portal, WebSite site)
        {
            site.Portal = portal;
            db.Sites.Add(site);
            db.SaveChanges();
            return true;
        }

        public bool UpdateSite(Portal portal, WebSite site)
        {
            db.Entry(site).State = EntityState.Modified;
            db.SaveChanges();
            return true;
        }

        public bool RemoveSite(Portal portal, string siteId)
        {
            var dbSite = db.Sites.FirstOrDefault(o => o.ID == siteId);
            if (dbSite == null)
                return false;
            db.Sites.Remove(dbSite);
            db.SaveChanges();
            return true;
        }

        public WebPage GetPageByUrl(WebSite site, string url)
        {
            var pages = db.Pages.OrderBy(o => o.MatchPriority).ToList();
            return pages.FirstOrDefault(o => o.WebSite.ID == site.ID && Regex.IsMatch(url, o.UrlPattern));
        }

        public WebPage GetPageByName(WebSite site, string name)
        {
            return db.Pages.FirstOrDefault(o => o.WebSite.ID == site.ID && o.Name == name);
        }

        #endregion

        #region IProvider Members

        public string Name
        {
            get { return "SqlPortalProvider"; }
        }

        #endregion
    }
}
